#!/usr/bin/env python
# -*- coding:utf-8 -*-

from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
from aliyunsdkcore.auth.credentials import AccessKeyCredential
from aliyunsdkcore.acs_exception.exceptions import ClientException, ServerException

from django.conf import settings


def send_sms_single(phone_num, template_id, template_param):
    """
    单条发送短信
    :param phone_num: 手机号
    :param template_id: 阿里云短信模板ID
    :param template_param: 短信模板所需参数，例如:{"code": "1234"}
    :return:
    """
    access_key_id = settings.ALIYUN_SMS_ACCESS_KEY_ID
    access_key_secret = settings.ALIYUN_SMS_ACCESS_KEY_SECRET
    sign_name = settings.ALIYUN_SMS_SIGN_NAME

    client = AcsClient(access_key_id, access_key_secret, 'cn-hangzhou')

    request = CommonRequest()
    request.set_method('POST')
    request.set_domain('dysmsapi.aliyuncs.com')
    request.set_version('2017-05-25')
    request.set_action_name('SendSms')

    request.add_query_param('RegionId', 'cn-hangzhou')
    request.add_query_param('PhoneNumbers', phone_num)
    request.add_query_param('SignName', sign_name)
    request.add_query_param('TemplateCode', template_id)
    request.add_query_param('TemplateParam', template_param)

    try:
        response = client.do_action_with_exception(request)
        return {
            'result': 0,
            'errmsg': '发送成功',
            'response': response.decode('utf-8')
        }
    except (ClientException, ServerException) as e:
        return {
            'result': 1000,
            'errmsg': f"发送失败：{e.message}",
            'response': str(e)
        }


def send_sms_multi(phone_num_list, template_id, template_param):
    """
    批量发送短信
    :param phone_num_list: 手机号列表
    :param template_id: 阿里云短信模板ID
    :param template_param: 短信模板所需参数，例如:{"code": "1234"}
    :return:
    """
    access_key_id = settings.ALIYUN_SMS_ACCESS_KEY_ID
    access_key_secret = settings.ALIYUN_SMS_ACCESS_KEY_SECRET
    sign_name = settings.ALIYUN_SMS_SIGN_NAME

    client = AcsClient(access_key_id, access_key_secret, 'cn-hangzhou')

    request = CommonRequest()
    request.set_method('POST')
    request.set_domain('dysmsapi.aliyuncs.com')
    request.set_version('2017-05-25')
    request.set_action_name('SendSms')

    request.add_query_param('RegionId', 'cn-hangzhou')
    request.add_query_param('PhoneNumbers', ','.join(phone_num_list))
    request.add_query_param('SignName', sign_name)
    request.add_query_param('TemplateCode', template_id)
    request.add_query_param('TemplateParam', template_param)

    try:
        response = client.do_action_with_exception(request)
        return {
            'result': 0,
            'errmsg': '发送成功',
            'response': response.decode('utf-8')
        }
    except (ClientException, ServerException) as e:
        return {
            'result': 1000,
            'errmsg': f"发送失败：{e.message}",
            'response': str(e)
        }